package moonhy.c2dm_client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import moonhy.c2dm_client.util.JSONSharedPreferences;
import moonhy.c2dm_client.util.httpConnectionManager;
import moonhy.c2dm_client.util.versionCodeManager;
import moonhy.c2dm_client.viewPages_Test.RegistrationResultActivity;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class C2DMRegistrationReceiver extends BroadcastReceiver {
	
	@Override
	public void onReceive(Context context, Intent intent) {
		final String serverURL = context.getString(R.string.SERVER_URL);
		String action = intent.getAction();
		Log.w("C2DM", "Registration Receiver called: ACTION : " + action);
		
		if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) {
			Log.w("C2DM", "Received registration ID");
			
			final String registrationId = intent.getStringExtra("registration_id");
			String error = intent.getStringExtra("error");

			Log.d("C2DM", "dmControl: registrationId = " + registrationId + ", error = " + error);
			String deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
			//createNotification(context, registrationId);

			sendRegistrationIdToServer(context, serverURL, deviceId, registrationId, getMyPhoneNumber(context));
			/*
			Intent i = new Intent(context, C2DM_ClientActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
			i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			PendingIntent p = PendingIntent.getActivity(context, 0,	i, PendingIntent.FLAG_UPDATE_CURRENT);
			
			try{
				p.send();
			}catch(CanceledException e){
				e.printStackTrace();
			}
			*/
		}
	}
	
	public String getMyPhoneNumber(Context context)
	{
	    return ((TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE)).getLine1Number();
	}

	private void saveRegistrationId(Context context, String registrationId, String phoneno) {
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		Editor edit = prefs.edit();
		edit.putString(context.getString(R.string.REG_ID), registrationId);
		edit.putString(context.getString(R.string.PHONE), phoneno);
		edit.commit();
		
		Log.w("C2DM", "Saving registration ID :" + registrationId + " -- " + phoneno);
	}
	

	public void createNotification(Context context, String registrationId) {
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.icon, "Registration successful", System.currentTimeMillis());
		// Hide the notification after its selected
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		Intent intent = new Intent(context, RegistrationResultActivity.class);
		intent.putExtra("registration_id", registrationId);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,	intent, 0);
		notification.setLatestEventInfo(context, "Registration", "Successfully registered", pendingIntent);
		notificationManager.notify(0, notification);
	}

	// Incorrect usage as the receiver may be canceled at any time
	// do this in an service and in an own thread
	public void sendRegistrationIdToServer(Context context, String SERV_URL, String deviceId, String registrationId, String phoneno) {
		StringBuilder builder = new StringBuilder();
		Log.w("C2DM", "Sending registration ID to my application server" + deviceId + " --" + registrationId + "phoneno");
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(SERV_URL + "register/register_proc.php");
		
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

			nameValuePairs.add(new BasicNameValuePair("deviceid", deviceId));
			nameValuePairs.add(new BasicNameValuePair("registrationid", registrationId));
			nameValuePairs.add(new BasicNameValuePair("phoneno", phoneno));
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(post);
			
			
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				saveRegistrationId(context, registrationId, phoneno);
				
				new initGroupInfo(context).execute();
				
			} else {
				Log.e("C2DM", "HttpConnection Error!!!!!!!!! " + statusCode);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
	private class initGroupInfo extends AsyncTask<Void, Void, Void>{
		private Context context;
		private int appVersion;
		private boolean mStatus = false;
		
		private initGroupInfo(Context context){
			this.context = context;
		}
		
		protected void onPreExecute(){	}
		
		protected Void doInBackground(Void... unused){
			
			//new versionCodeManager(context);
			
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
			Editor edit = prefs.edit();
			
			try {
				httpConnectionManager hcm = new httpConnectionManager(context);
				
				JSONObject json = new JSONObject(hcm.readJSON(context.getString(R.string.SERVER_URL) + "info/service_group_info.php", null));
				JSONArray groupInfo = json.getJSONArray("data_result");
				JSONObject groupInfoJSONObject = groupInfo.getJSONObject(0);
				JSONSharedPreferences.saveJSONObject(context, "gline", "groupInfo", groupInfoJSONObject);
				
				JSONObject myInfo = json.getJSONObject("my_info");
				edit.putInt("MEM_SEQ", myInfo.getInt("MEM_SEQ"));
				edit.putInt("MEM_AUTH", myInfo.getInt("MEM_AUTH"));
				edit.putString("MEM_NAME", myInfo.getString("MEM_NAME"));
				edit.putString("MEM_JOIN_DATE", myInfo.getString("MEM_JOIN_DATE"));
				
				
				JSONObject serviceJSON = new JSONObject(hcm.readJSON(context.getString(R.string.SERVER_URL) + "members/member_list.php", null));
				JSONArray memberInfo = serviceJSON.getJSONArray("data_result");
				JSONSharedPreferences.saveJSONArray(context, "gline", "memberInfo", memberInfo);
				
				
//				JSONObject noticeJSON = new JSONObject(hcm.readJSON(context.getString(R.string.SERVER_URL) + "notice/notice_list.php", null));
//				JSONArray noticeInfo = noticeJSON.getJSONArray("data_result");
//				JSONSharedPreferences.saveJSONArray(context, "gline", "noticeInfo", noticeInfo);
				
				
				edit.putInt("APP_VERSION_SERVER", groupInfoJSONObject.getInt("APP_VERSION"));
				edit.commit();
				
				/*
				
				SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
				Editor edit = prefs.edit();
				edit.putInt("GROUP_CREATED_DATE", groupInfoJSONObject.getInt("GROUP_CREATED_DATE"));
				edit.putInt("GROUP_BALANCE", groupInfoJSONObject.getInt("GROUP_BALANCE"));
				edit.commit();
				*/
				
	        }catch(Exception e){
	        	
	        }
	        return null;
	    }

	    protected void onPostExecute(Void unused){
	    	SplashScreen.isRegstered = true;
	    	//SplashScreen.mSplashThread.start();
	    	//SplashScreen.finalizeActivity();
	    }

	}
}